from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

import os, time


class LAYER():
    def __init__(self):
        self.folds = []

class FOLD():
    def __init__(self):
        self.fold_name = None
        self.type = None
        self.element = None
        self.label = None
        self.next = None

class Weiyun():
    def __init__(self):
        self.weiyun = "http://www.weiyun.com"
        fp = webdriver.FirefoxProfile()
        fp.set_preference("browser.download.folderList", 2)
        fp.set_preference("browser.download.manager.showhenStarting", True)
        fp.set_preference("browser.download.dir", os.getcwd())
        fp.set_preference("browser.download.manager.showAlertOnComplete", False)
        fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream, text/csv, application/zip, application/x-gzip, image/jpeg")#下载文件类型
        
        self.driver = webdriver.Firefox(firefox_profile = fp)
        self.wait = WebDriverWait(self.driver, 10)
        self.driver.implicitly_wait(10) # seconds
        self.layer = None

    def refresh(self):
        import time
        time.sleep(3)
        self.driver.refresh()
        self.driver.get(self.driver.current_url)
        self.wait.until(EC.presence_of_element_located((By.CLASS_NAME,"user-info")))
        time.sleep(0.8)

    def login(self):
        self.driver.get(self.weiyun)
        try:
            element = self.wait.until(EC.presence_of_element_located((By.ID,"login")))
            self.driver.switch_to.frame("qq_login_iframe")
            hidden_submenu = self.driver.find_element_by_id("switcher_plogin")
            hidden_submenu.send_keys(Keys.ENTER)
        except TimeoutException as e:
            pass
        else:
            user = os.environ['user']
            passw = os.environ['passw']
            self.driver.find_element_by_id('u').send_keys(user)
            self.driver.find_element_by_id('p').send_keys(passw)
            self.driver.find_element_by_id('login_button').send_keys(Keys.ENTER)

            self.refresh()
            try:
                self.wait.until(EC.presence_of_element_located((By.CLASS_NAME,"user-info")))
            except TimeoutException as e:
                raise Exception("Login Fail")
        finally:
            pass
            # driver.quit()
    
    def menu_dir(self, foldname):
        menus = self.driver.find_elements_by_xpath("//span[@class='menu-tit']")
        for m in menus:
            if foldname == m.text:
                action = ActionChains(self.driver)
                action.move_to_element(m)
                action.click().perform()
                break
        
    def list_dir(self):
        # dir_list = self.driver.find_elements_by_xpath("//li[@class='list-group-item checked']")
        dir_list = self.driver.find_elements_by_xpath("//a[@class='tit']")
        label_list = self.driver.find_elements_by_xpath("//div[@class='label']")
        self.layer = LAYER()
        for index, ele in enumerate(dir_list):
            # a = ele.find_element_by_class_name("tit")
            f = FOLD()                   
            f.fold_name = ele.text
            f.element = ele
            f.label = label_list[index]
            self.layer.folds.append(f)
        return (i.fold_name for i in self.layer.folds)

    def cd(self, fold_name):
        self.list_dir()
        for f in self.layer.folds:
            if (fold_name == f.fold_name):
                f.element.find_element_by_xpath("//a[@class='tit']").send_keys(Keys.ENTER)
                break

    def reversal_select(self):
        list_group = None
        xpath = None
        if self.is_selected():
            xpath = "//div[@class='list-group-tit name checked up']"
            icon_check_box = self.driver.find_element_by_xpath(xpath)
        else:
            xpath = "//div[@class='list-group-tit name up']"
            icon_check_box = self.driver.find_element_by_xpath(xpath).find_element_by_class_name("icon icon-check-s icon-checkbox")
        action = ActionChains(self.driver)
        action.move_to_element(icon_check_box)
        action.click().perform()
    
    def is_selected(self):
        try:
            self.driver.find_element_by_xpath("//div[@class='list-group-tit name checked up']")
        except:
            return False
        else:
            return True


    def select(self, fold_name):
        self.list_dir()
        action = ActionChains(self.driver)
        for f in self.layer.folds:
            if (fold_name == f.fold_name):
                check_box = f.label
                # .find_element_by_class_name("label")
                action.move_to_element(check_box)
                action.click()
                # check_box.send_keys(Keys.ENTER)
        action.perform()
        time.sleep(.2)
    
    def download(self):
        """
        will download files which is selected before
        """
        # check file is select first( need to impelement)
        action = ActionChains(self.driver)
        # download = self.driver.find_elements_by_xpath("//div[@class='mod-action-wrap mod-action-wrap-menu clearfix']/div[@class='action-item']")[0]
        download = self.driver.find_elements_by_xpath("//span[@class='act-txt']")
        for i in download:
            if i.text == "下载":
                print(download.text)
                action.move_to_element(download)
                action.click()
                action.perform()
                # download.click()

    def delete(self):
        """
        will delete files which is selected before
        """
        action = ActionChains(self.driver)
        delete = self.driver.find_elements_by_xpath("//span[@class='act-txt']")
        for i in delete:
            if i.text == "删除":
                action.move_to_element(i)
                action.click()
                action.perform()
                sure = self.driver.find_element_by_xpath("//div[@class='modal-dialog modal-dialog-400 modal-dialog-confirm']/div[@class='modal-dialog-ft clearfix btn-group']/button[@class='btn btn-active']")
                action.move_to_element(sure)
                action.click()
                action.perform()

    # def __del__(self):
    #     self.driver.close()

if __name__ == "__main__":
    weiyun = Weiyun()
    weiyun.login()

    # print(list(weiyun.menu_dir()))

    # weiyun.list_dir()
    # weiyun.cd("备份")
    # for f in weiyun.list_dir():
    #     weiyun.select(f)
    # weiyun.reversal_select()
    # for f in weiyun.list_dir():
    #     weiyun.select(f)
    
    # weiyun.reversal_select()
    # for f in list(weiyun.list_dir())[::-1]:
    #     weiyun.select(f)
    # weiyun.reversal_select()
    # for f in list(weiyun.list_dir())[::2]:
    #     weiyun.select(f)

    # weiyun.download()

    # weiyun.delete()
    